﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Acme.Sakila.TestSite.Objects;
using Acme.Sakila.EFDAL;

namespace Acme.Sakila.TestSite
{
	public partial class CustomerItem : BasePersistablePage
	{
		#region Page Events

		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);
			cmdSave.Click += new EventHandler(SaveData);
			cmdCancel.Click += new EventHandler(cmdCancel_Click);
		}

		#endregion

		#region Methods

		protected override nHydrate.EFCore.DataAccess.NHEntityObject CreateObject(SakilaEntities context)
		{
			var newItem = new Acme.Sakila.EFDAL.Entity.customer();
			context.AddItem(newItem);
			return newItem;
		}

		protected override void SetupBindings(SakilaEntities context)
		{
			var customerId = this.Request["id"].ToInt32();
			var customer = context.customer.FirstOrDefault(x => x.customer_id == customerId);
			if (customer == null)
				customer = CreateObject(context) as Acme.Sakila.EFDAL.Entity.customer;

			Mapper.Map(lblCustomerId, customer, Acme.Sakila.EFDAL.Entity.customer.FieldNameConstants.customer_id);
			Mapper.Map(txtEmail, customer, Acme.Sakila.EFDAL.Entity.customer.FieldNameConstants.email, lblEmail);
			Mapper.Map(txtFirstName, customer, Acme.Sakila.EFDAL.Entity.customer.FieldNameConstants.first_name, lblFirstName);
			Mapper.Map(txtLastName, customer, Acme.Sakila.EFDAL.Entity.customer.FieldNameConstants.last_name, lblLastName);

			linkPayments.NavigateUrl = "/PaymentList.aspx?customerid=" + customerId;
			linkRentals.NavigateUrl = "/RentalList.aspx?customerid=" + customerId;

			var addressText = string.Empty;
			if (customer.address != null)
			{
				addressText += customer.address.address1 + "<br />";
				if (customer.address.city != null)
				{
					addressText += customer.address.city.name;
					addressText += customer.address.postal_code + "<br />";
					if (customer.address.city.country != null)
					{
						addressText += customer.address.city.country.name + "<br />";
					}
				}
			}
			lblAddress.Text = addressText;

		}

		#endregion

		#region Event Handlers

		private void cmdCancel_Click(object sender, EventArgs e)
		{
			this.Response.Redirect(SessionHelper.LastCustomerListSearch);
		}

		protected override void OnDataSavedSucess(EventArgs e)
		{
			base.OnDataSavedSucess(e);
			this.Response.Redirect(SessionHelper.LastCustomerListSearch);
		}

		#endregion

	}
}